<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="关联设备" prop="deviceIds">
            <!-- <el-input v-model="queryParams.deviceIds" placeholder="请输入关联设备" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.deviceIds" placeholder="请选择关联设备" clearable>
              <el-option v-for="dict in deviceInfoList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['device:telCall:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:telCall:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['device:telCall:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:telCall:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 370px)"
        stripe
        v-loading="loading"
        :data="telCallList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row)=>handleUpdate(row)"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="关联设备" align="center" prop="deviceText" />
        <el-table-column label="生效日期" align="left" prop="dayOfWeekText" />
        <el-table-column label="可用时段" align="center">
          <template #default="scope">
            <p v-for="(item,index) in ['早上','中午','晚上']" :key="index" class="timeOfDay">{{ item }} ： {{ scope.row.rules[item] }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:telCall:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:telCall:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改话机使用时段对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="telCallFormRef" :model="form" label-width="100px">
        <el-form-item label="生效日期" prop="dayOfWeek">
          <el-checkbox-group v-model="dayOfWeeks">
            <el-checkbox v-for="item in dayOfWeekOptions" :key="item.value" :label="item.value" :value="item.value">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="可使用时段">
          <div class="use_time">
            <section class="chunk">
              <span>早上:</span>
              <div class="item">
                <section>
                  <div v-for="(item, index) in timeOfDay1" :key="item.uuid">
                    <el-time-picker
                      v-model="item.value"
                      is-range
                      range-separator="~"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      disabled-seconds
                      value-format="HH:mm"
                    />
                    <el-button type="danger" icon="Delete" @click="timeOfDayDel(timeOfDay1,index)" />
                  </div>
                </section>
                <el-button type="primary" icon="Plus" class="add" @click="timeOfDayAdd(timeOfDay1)" />
              </div>
            </section>
            <section class="chunk">
              <span>中午:</span>
              <div class="item">
                <section>
                  <div v-for="(item, index) in timeOfDay2" :key="item.uuid">
                    <el-time-picker
                      v-model="item.value"
                      is-range
                      range-separator="~"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      disabled-seconds
                      value-format="HH:mm"
                    />
                    <el-button type="danger" icon="Delete" @click="timeOfDayDel(timeOfDay2,index)" />
                  </div>
                </section>
                <el-button type="primary" icon="Plus" class="add" @click="timeOfDayAdd(timeOfDay2)" />
              </div>
            </section>
            <section class="chunk">
              <span>晚上:</span>
              <div class="item">
                <section>
                  <div v-for="(item, index) in timeOfDay3" :key="item.uuid">
                    <el-time-picker
                      v-model="item.value"
                      is-range
                      range-separator="~"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      disabled-seconds
                      value-format="HH:mm"
                    />
                    <el-button type="danger" icon="Delete" @click="timeOfDayDel(timeOfDay3,index)" />
                  </div>
                </section>
                <el-button type="primary" icon="Plus" class="add" @click="timeOfDayAdd(timeOfDay3)" />
              </div>
            </section>
          </div>
        </el-form-item>
        <el-form-item label="关联设备" prop="deviceIds">
          <el-select v-model="deviceIds" placeholder="请选择关联设备" clearable multiple style="width: 80%;">
            <el-option v-for="dict in deviceInfoList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <p class="tip">注：设置规则时设备在线才能生效，离线设置需要在线之后才能更新规则；</p>
        <p class="red">请按24小时制设置可使用时间</p>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TelCall" lang="ts">
import { listTelDevice, getTelDevice, delTelDevice, addTelDevice, updateTelDevice, restartDevice } from '@/api/device/telDevice';
import { TelDeviceVO, TelDeviceQuery, TelDeviceForm } from '@/api/device/telDevice/types';
import { listTelCall, getTelCall, delTelCall, addTelCall, updateTelCall } from '@/api/device/telCall';
import { listDeviceInfo } from '@/api/device/deviceInfo';
import { TelCallVO, TelCallQuery, TelCallForm } from '@/api/device/telCall/types';
import { DeviceInfoVO, DeviceInfoForm, DeviceInfoQuery } from '@/api/device/deviceInfo/types';
import { uuid } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const deviceInfoList = ref<TelDeviceVO[]>([]);
const telCallList = ref<TelCallVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const timeOfDay1 = ref<Array<any>>([]);
const timeOfDay2 = ref<Array<any>>([]);
const timeOfDay3 = ref<Array<any>>([]);
const dayOfWeekOptions = reactive([
  {
    value: 2,
    label: '周一'
  },
  {
    value: 3,
    label: '周二'
  },
  {
    value: 4,
    label: '周三'
  },
  {
    value: 5,
    label: '周四'
  },
  {
    value: 6,
    label: '周五'
  },
  {
    value: 7,
    label: '周六'
  },
  {
    value: 1,
    label: '周日'
  }
]);
const dayOfWeeks = ref<Array<any>>([]);
const deviceIds = ref<Array<any>>([]);

const queryFormRef = ref<ElFormInstance>();
const telCallFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TelCallForm = {
  id: undefined,
  dayOfWeek: undefined,
  deviceIds: undefined
};
const data = reactive<PageData<TelCallForm, TelCallQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dayOfWeek: undefined,
    deviceIds: undefined,
    params: {}
  },
  rules: {
    dayOfWeek: [{ required: true, message: '生效日期不能为空', trigger: 'blur' }],
    deviceIds: [{ required: true, message: '关联设备不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const dataDevice = reactive<PageData<TelDeviceForm, TelDeviceQuery>>({
  queryParams: {
    pageNum: 1,
    terminalKey: undefined,
    terminalMac: undefined,
    name: undefined,
    series: undefined,
    ip: undefined,
    deviceCode: undefined,
    heartbeatFrequency: undefined,
    timeOn: undefined,
    timeOff: undefined,
    onlineStatus: undefined,
    offlineTime: undefined,
    status: 1,
    params: {}
  }
});

const { queryParams: deviceQueryParams } = toRefs(dataDevice);

/** 查询话机使用时段列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTelCall(queryParams.value);
  for (let row of res.rows) {
    if (row.ruleText) {
      row['rules'] = JSON.parse(row.ruleText);
    } else {
      row['rules'] = {};
    }
  }
  telCallList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  telCallFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TelCallVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  initForm();
  dialog.visible = true;
  dialog.title = '添加话机使用时段';
};

const initForm = () => {
  dayOfWeeks.value = [];
  deviceIds.value = [];
  timeOfDay1.value = [
    {
      uuid: uuid(),
      startTime: '',
      endTime: '',
      value: ''
    }
  ];
  timeOfDay2.value = [
    {
      uuid: uuid(),
      startTime: '',
      endTime: '',
      value: ''
    }
  ];
  timeOfDay3.value = [
    {
      uuid: uuid(),
      startTime: '',
      endTime: '',
      value: ''
    }
  ];
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TelCallVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTelCall(_id);
  dayOfWeeks.value = res.data?.dayOfWeek.split(',').map(Number);
  deviceIds.value = res.data?.deviceIds.split(',');
  timeOfDay1.value = [];
  timeOfDay2.value = [];
  timeOfDay3.value = [];
  for (let r of res.data.rules) {
    if (r.timeOfDay == 1) {
      timeOfDay1.value.push({
        uuid: r.id,
        startTime: r.startTime,
        endTime: r.endTime,
        value: [r.startTime, r.endTime]
      });
    }
    if (r.timeOfDay == 2) {
      timeOfDay2.value.push({
        uuid: r.id,
        startTime: r.startTime,
        endTime: r.endTime,
        value: [r.startTime, r.endTime]
      });
    }
    if (r.timeOfDay == 3) {
      timeOfDay3.value.push({
        uuid: r.id,
        startTime: r.startTime,
        endTime: r.endTime,
        value: [r.startTime, r.endTime]
      });
    }
  }
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改话机使用时段';
};

const adjustTimeOfDay = (timeOfDay: number, data: Array<any>) => {
  const list = [];
  let orderNum = 1;
  for (let item of data) {
    item['timeOfDay'] = timeOfDay;
    item.startTime = item.value[0];
    item.endTime = item.value[1];
    item['orderNum'] = orderNum;
    orderNum++;
    list.push(item);
  }
  return list;
};

/** 提交按钮 */
const submitForm = () => {
  telCallFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const timeOfDays = [...timeOfDay1.value, ...timeOfDay2.value, ...timeOfDay3.value];
      if (timeOfDays.length == 0) {
        return proxy?.$modal.msgError('请至少添加一个时间段');
      }
      for (let item of timeOfDays) {
        if (item.value.length == 0) {
          return proxy?.$modal.msgError('请填写完整时间段');
        }
      }
      const timeOfDayList = [
        ...adjustTimeOfDay(1, timeOfDay1.value),
        ...adjustTimeOfDay(2, timeOfDay2.value),
        ...adjustTimeOfDay(3, timeOfDay3.value)
      ];
      buttonLoading.value = true;
      let param: any = {
        id: form.value['id'],
        dayOfWeek: dayOfWeeks.value.join(','),
        deviceIds: deviceIds.value.join(','),
        rules: timeOfDayList
      };
      let tipText = '修改成功';
      if (form.value.id) {
        await updateTelCall(param).finally(() => (buttonLoading.value = false));
      } else {
        tipText = '新增成功';
        await addTelCall(param).finally(() => (buttonLoading.value = false));
      }
      buttonLoading.value = false;
      proxy?.$modal.msgSuccess(tipText);
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TelCallVO) => {
  const _ids = row?.id || ids.value;
  let tipText = '是否确认删除选中的数据？';
  if (row?.id) {
    tipText = '是否确认删除"' + row.deviceText + '"的数据项？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  await delTelCall(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'device/telCall/export',
    {
      ...queryParams.value
    },
    `telCall_${new Date().getTime()}.xlsx`
  );
};
const getDeviceInfoList = async () => {
  const res = await listTelDevice(deviceQueryParams.value);
  deviceInfoList.value = res.rows;
};

const timeOfDayDel = (datas: Array<any>, index: number) => {
  datas = datas.splice(index, 1);
};

const timeOfDayAdd = (datas: Array<any>) => {
  datas.push({
    uuid: uuid(),
    startTime: '',
    endTime: '',
    value: ''
  });
  console.log(datas);
};

onMounted(() => {
  getList();
  getDeviceInfoList();
});
</script>

<style scoped lang="scss">
.tip {
  color: #999;
}
.red {
  color: red;
}

.use_time {
  display: flex;
  flex-direction: column;
}
.chunk {
  display: flex;
  margin-bottom: 20px;
  span {
    width: 50px;
  }
  .item {
    flex: 1;
    display: flex;
    align-items: center;
    section {
      flex: 1;
    }
    div {
      display: flex;
      align-items: center;
      padding: 5px;
      .el-button {
        margin-left: 10px;
      }
    }
    .add {
      margin-left: 20px;
    }
  }
}
.timeOfDay {
  padding: 0;
  margin: 0;
  text-align: left;
}
</style>
